import { Component, Prop, Vue, Watch, PropSync } from 'vue-property-decorator'
import style from './style.less'
import styles from '@/views/NewApply/NewApply.less'
import OperationCol from '@/components/OperationCol'
import SealStatus, { issueList } from '@/components/SealStatus'
import SealDetail from '@/views/AppliedForMe/SealDetail'
import { desensitization } from '@/lib/utils'
import {
  orgLicenseTypes,
  orgTypes,
  userLicenseTypes,
  adminTypes,
  useTypes,
  formatStatus,
  sealTypes,
} from '@/lib/sealFormat'
import { Action } from 'vuex-class'
import { ElTable } from 'element-ui/types/table'
import TableEmpty from '@/components/tableEmpty'

@Component({})
export default class SealDrawer extends Vue {
  sealType: number[] = []
  status: number[] = []
  sealName: string = ''
  sealCode: string = ''
  pageIndex: number = 1
  pageSize: number = 10
  footerHeight: number = 0
  sealList: any[] = []
  total: number = 0
  loading: boolean = false
  detailVisible: boolean = false
  sealData: any = {}
  selectList: any[] = []
  showFooter: boolean = false
  showInput: boolean = false // 控制组件自动focus

  @Prop({ default: '' }) project!: any // 项目检索条件
  @Prop({ default: false }) isSelect!: boolean // 是否可选择进行印章授权取消
  @Prop({ default: '' }) title!: string
  @Prop({ default: false }) isAll!: boolean // 是否为全部授权的应用
  // @Prop({ default: () => [] })  selectApp!: any[]
  @PropSync('visible', { default: false }) drawer!: boolean

  @Action('project/cancelAuthorizeAllManageSeal')
  cancelAuthorizeAllManageSeal!: any
  @Action('project/cancelAuthorizeManageSeal')
  cancelAuthorizeManageSeal!: any
  @Action('myManagingSeal/sealDetail') sealDetail!: any
  @Action('project/queryManageSealProjectAuthorizeSeal')
  queryManageSealProjectAuthorizeSeal!: any
  protected render(h: any) {
    return (
      <div class={style.drawer}>
        <el-drawer
          size={'1100px'}
          close-on-press-escape={false}
          visible={this.drawer}
          show-close={false}
          modal-append-to-body={false}
          onOpened={this.opened}
          {...{
            on: {
              'update:visible': this.visibleChange,
            },
          }}
          with-header
        >
          <p slot="title">
            <i
              class="el-icon-close"
              onClick={() => this.visibleChange(false)}
            />
            {this.title}
          </p>
          <div
            class={style.orderList}
            v-show={this.showInput}
            style={{
              height: `calc(100% - ${this.footerHeight}px)`,
            }}
          >
            <div
              class={{
                [styles.query]: true,
                custom: true,
                [style.query]: true,
              }}
            >
              <span class={[styles.part]}>
                <span class={styles.part}>
                  <span>印章名称</span>
                  <el-input v-model={this.sealName} />
                </span>
                <span>印章类别</span>
                <el-select
                  v-model={this.sealType}
                  multiple
                  collapse-tags
                  placeholder="默认全部"
                >
                  {sealTypes.map((sealType: any, index: number) => (
                    <el-option
                      key={sealType.id}
                      label={sealType.value}
                      value={sealType.id}
                    />
                  ))}
                </el-select>
              </span>
              <span class={styles.part}>
                <span>印章编码</span>
                <el-input v-model={this.sealCode} />
              </span>
              <span class={styles.part}>
                <span>印章状态</span>
                <el-select
                  v-model={this.status}
                  multiple
                  collapse-tags
                  placeholder="默认全部"
                >
                  {issueList
                    .filter(sealType => sealType.key !== 3)
                    .map((sealType: any, index: number) => (
                      <el-option
                        key={sealType.key}
                        label={sealType.text}
                        value={sealType.key}
                      />
                    ))}
                </el-select>
              </span>

              <span class={[styles.part, style.right]}>
                <el-button
                  plain
                  class="min color-blue"
                  loading={this.loading}
                  onClick={this.query}
                >
                  搜索
                </el-button>
                <el-button plain class="min color-gray" onClick={this.reset}>
                  重置
                </el-button>
              </span>
            </div>
            <el-table
              data={this.sealList}
              style="width: 100%"
              v-loading={this.loading}
              ref="table"
              onSelect={this.selectHandle}
              onSelect-all={this.selectAllHandle}
            >
              <TableEmpty
                slot="empty"
                msg="当前查询条件下暂无已授权印章"
                url={require('@/assets/seal-empty.svg')}
                v-show={!this.loading}
              />
              {this.isSelect && (
                <el-table-column
                  //   selectable={this.selectable}
                  type="selection"
                  width="55"
                />
              )}
              <el-table-column
                prop="sealCode"
                label="印章编码"
                min-width="180"
                show-overflow-tooltip
              />
              <el-table-column
                prop="sealName"
                label="印章名称"
                min-width="180"
                show-overflow-tooltip
              />
              <el-table-column
                prop="sealType"
                label="印章类别"
                min-width="80"
                show-overflow-tooltip
                {...{
                  scopedSlots: {
                    default: (scope: any) => {
                      return formatStatus(sealTypes, scope.row.sealType)
                    },
                  },
                }}
              />
              <el-table-column
                prop="organizeName"
                label="用章机构名称"
                min-width="100"
                show-overflow-tooltip
              />
              <el-table-column
                prop="endTime"
                label="到期时间"
                show-overflow-tooltip
              />
              <el-table-column
                prop="sealStatus"
                label="状态"
                min-width="100"
                {...{
                  scopedSlots: {
                    default: (scope: any) => {
                      return <SealStatus issue status={scope.row.sealStatus} />
                    },
                  },
                }}
              />

              {this.isSelect && (
                <el-table-column
                  prop="id"
                  label="操作"
                  width="80"
                  {...{
                    scopedSlots: {
                      default: (scope: any) => {
                        return (
                          <span>
                            <OperationCol
                              operations={this.getOperations}
                              showNum={4}
                              row={scope.row}
                              index={scope.$index}
                            />
                          </span>
                        )
                      },
                    },
                  }}
                />
              )}
            </el-table>
            {this.sealList && this.sealList.length > 0 && (
              <el-pagination
                class={{ [styles.pagination]: true }}
                onSize-change={this.handleSizeChange}
                onCurrent-change={this.handleCurrentChange}
                current-page={this.pageIndex}
                page-sizes={[10, 20, 30]}
                page-size={this.pageSize}
                layout="total, sizes, prev, pager, next, jumper"
                total={this.total}
                pager-count={5}
              />
            )}
          </div>
          {this.showFooter && (
            <div class={style.pagination} ref="footer">
              <div class={style.selection}>
                <p class={style.tagName}>
                  <i class="el-icon-info" />
                  已选择应用
                </p>
                <div class={style.tags}>
                  {[this.project].map((tag: any) => (
                    <el-tag
                      key={tag.projectId}
                      closable={false}
                      disable-transitions={false}
                    >
                      {tag.projectName}
                    </el-tag>
                  ))}
                </div>
              </div>
              <div class={style.selection}>
                <p class={style.tagName}>已选择印章</p>
                <div class={style.tags}>
                  {this.selectList &&
                    this.selectList.map((tag: any) => (
                      <el-tag
                        key={tag.sealCode}
                        closable
                        disable-transitions={false}
                        onClose={() => this.deleteSeal(tag)}
                      >
                        {tag.sealName}
                      </el-tag>
                    ))}
                </div>
              </div>
              <div class={style.operations}>
                {/* {this.isAll && ( */}
                <el-button
                  type="primary"
                  class={['bg-color-blue', { [style.medium]: true }]}
                  onClick={this.allAuth}
                >
                  全部取消授权
                </el-button>
                {/* )} */}
                <el-button
                  type="primary"
                  class={['bg-color-blue', { [style.medium]: true }]}
                  onClick={this.partAuth}
                  disabled={this.selectList.length === 0}
                >
                  取消授权
                </el-button>
                <span class={style.info}>
                  当前选中<span>{this.selectList.length}</span>枚印章，共
                  <span>{this.getOrgCount()}</span>
                  个机构
                </span>
              </div>
            </div>
          )}
          <SealDetail
            onVisibleChange={(val: boolean) => {
              this.detailVisible = val
            }}
            data={this.sealData}
            visible={this.detailVisible}
          />
        </el-drawer>
      </div>
    )
  }
  @Watch('selectList.length')
  selectListChange(val: number) {
    this.showSelects()
    this.getPaddingBottom()
  }

  @Watch('drawer')
  visibleHandle(val: boolean) {
    if (val) {
      this.showInput = false
      this.reset()
      this.getPaddingBottom()
    }
  }

  visibleChange(val: boolean) {
    // this.getPaddingBottom()
    this.drawer = val
    if (!val) {
      this.showFooter = false
    }
  }

  get getOperations() {
    const btns: any[] = [
      {
        id: 1,
        text: '详情',
        onClick: (index: number, rows: any) => {
          this.detail(rows)
        },
      },
    ]

    return btns
  }

  handleSizeChange(val: number) {
    this.pageIndex = 1
    this.pageSize = val
    this.queryList()
  }

  handleCurrentChange(val: number) {
    this.pageIndex = val
    this.queryList()
  }

  async queryList() {
    this.loading = true
    await this.queryManageSealProjectAuthorizeSeal({
      projectId: (this.project || {}).projectId,
      sealCode: this.sealCode,
      sealTypes: this.sealType,
      sealStatus: this.status,
      sealName: this.sealName,
      pageIndex: this.pageIndex,
      pageNumber: this.pageSize,
    })
      .then((res: any) => {
        this.sealList = (res || {}).list || []
        this.total = res.total || 0
      })
      .catch(() => {})
    this.loading = false
    const table = this.$refs.table as ElTable
    table && table.doLayout()
    this.showSelects()
  }
  query() {
    this.pageIndex = 1
    this.queryList()
  }

  reset() {
    this.sealName = ''
    this.sealCode = ''
    this.status = []
    this.sealType = []
    this.query()
  }

  selectHandle(selection: any[], row: any) {
    if (
      this.selectList.findIndex(a => {
        return a.sealCode === row.sealCode
      }) < 0
    ) {
      this.selectList = this.selectList.concat([row])
    } else {
      const list = this.selectList
      list.splice(
        this.selectList.findIndex(a => {
          return a.sealCode === row.sealCode
        }),
        1
      )
      //   this.$emit('selectChange', list)
      this.selectList = list
    }
  }

  selectAllHandle(selection: any) {
    // if (!this.multi) {
    //   ;(this.$refs.table as ElTable).clearSelection()
    //   // if (this.selectList.length !== 0) {
    //   // this.sealList.map(app => {
    //   //   if (
    //   //     this.selectList.filter(select => select.id === app.id)
    //   //       .length > 0
    //   //   ) {
    //   //     ;(this.$refs.table as ElTable).toggleRowSelection(app)
    //   //   }

    //   //   return {}
    //   // })
    //   this.showSelects()
    //   this.$emit('selectChange', this.selectList)
    //   // }

    //   return
    // }
    if (selection.length === 0) {
      const list = this.selectList.filter((select: any) => {
        return (
          this.sealList.findIndex(a => {
            return a.sealCode === select.sealCode
          }) < 0
        )
      })
      this.selectList = list
    } else {
      const arr = this.selectList.concat(selection)
      //   this.$emit('selectChange', this.unique(arr))
      this.selectList = this.unique(arr)
    }
  }

  showSelects() {
    // 部门列表懒加载、tag和列表checkbox联动时同步列表的checkbox数据
    this.$nextTick(() => {
      ;(this.$refs.table as ElTable) &&
        (this.$refs.table as ElTable).clearSelection()
      this.sealList.map(app => {
        if (
          this.selectList.filter(
            (select: any) => select.sealCode === app.sealCode
          ).length > 0
        ) {
          ;(this.$refs.table as ElTable) &&
            (this.$refs.table as ElTable).toggleRowSelection(app)
        }

        return app
      })
    })
  }
  unique(arr: any[]) {
    // 去重
    return arr.filter(function(item, index, arr) {
      // 当前元素，在原始数组中的第一个索引==当前索引值，否则返回当前元素
      return (
        arr.findIndex(a => {
          return a.sealCode === item.sealCode
        }) === index
      )
    })
  }

  detail(row: any) {
    this.sealDetail(row.sealSn).then((data: any) => {
      this.sealData = Object.assign({}, data, {
        organizeType: formatStatus(orgTypes, data.organizeType),
        organizeCardType: formatStatus(orgLicenseTypes, data.organizeCardType),
        organizeLevel: formatStatus(adminTypes, data.organizeLevel),
        inspectCardType: formatStatus(userLicenseTypes, data.inspectCardType),
        sealType: formatStatus(sealTypes, data.sealType),
        sealUseType: formatStatus(useTypes, data.sealUseType),
        inspectMobileDes: desensitization(data.inspectMobile),
        inspectCardIdDes: desensitization(data.inspectCardId),
      })
      this.detailVisible = true
    })
  }

  deleteSeal(seal: any) {
    this.selectList = this.selectList.filter(
      (select: any) => seal.sealCode !== select.sealCode
    )
  }

  partAuth() {
    if (this.selectList.length === 0) {
      this.$message.warning('请选择取消授权印章')

      return
    }
    const projectIds = [this.project.projectId]
    const sealCodes = this.selectList.map(seal => seal.sealCode) || []
    this.loading = true
    this.cancelAuthorizeManageSeal({ projectId: projectIds[0], sealCodes })
      .then((res: any) => {
        this.loading = false
        this.$router.push({
          name: 'authorizeResult',
          query: {
            id: this.project.projectId,
            name: this.project.projectName,
            cancel: '1',
          },
        })
      })
      .catch(() => {
        this.loading = false
      })
  }

  allAuth() {
    // 全部授权
    this.$confirm('确认取消授权当前所有印章？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnPressEscape: false,
      closeOnClickModal: false,
      customClass: 'custom-confirm',
    })
      .then(() => {
        this.confirmCancel()
      })
      .catch(() => {})
  }
  confirmCancel() {
    const projectIds = [this.project.projectId]
    this.loading = true
    this.cancelAuthorizeAllManageSeal({ projectId: projectIds[0] })
      .then((res: any) => {
        this.loading = false
        this.$router.push({
          name: 'authorizeResult',
          query: {
            id: this.project.projectId,
            name: this.project.projectName,
            cancel: '1',
          },
        })
      })
      .catch(() => {
        this.loading = false
      })
  }
  getOrgCount() {
    // 获取机构数量
    return [...new Set(this.selectList.map(seal => seal.organizeUUID))].length
  }

  getPaddingBottom() {
    this.$nextTick(() => {
      this.footerHeight = (
        (this.$refs.footer as any) || { offsetHeight: 0 }
      ).offsetHeight
    })
  }

  mounted() {
    this.getPaddingBottom()
  }

  opened() {
    this.showFooter = this.isSelect
    this.getPaddingBottom()
    this.$nextTick(() => {
      this.showInput = true
    })
  }
}
